package com.lipiao.makerandroid.View.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lipiao.makerandroid.Bean.RespondBean.ReadBean;
import com.lipiao.makerandroid.R;
import com.lipiao.makerandroid.Utils.HttpUtil;
import com.lipiao.makerandroid.View.Activity.ReadActivity;
import com.lipiao.makerandroid.View.Adapter.CollectionAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CollectionFragment extends Fragment{
    static String TAG = "CollectFragment";
    static String userNumber;

    RecyclerView mRecyclerView;

    RefreshLayout refreshLayout;

    private List<ReadBean> mList = new ArrayList<>();
    View rootView;
    Unbinder unbinder;

    CollectionAdapter collectionAdapter;

    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            collectionAdapter.setReadBeanList(mList);
        }
    };
    public CollectionFragment() {

    }

    public static CollectionFragment newInstance(String userNumber) {
        System.out.println("newInstance");
//        System.out.println("===lllll=================");
        CollectionFragment fragment = new CollectionFragment();
//        Log.i(TAG,"kkkkkkkkkkk");
        Bundle bundle = new Bundle();
        bundle.putString("userNumber", userNumber);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_system, container, false);
        //返回一个Unbinder值（进行解绑），这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, rootView);
        assert getArguments() != null;//判空处理
        userNumber = getArguments().getString("userNumber");//获取账号
        initView(rootView);
        fetchData();
        return rootView;
    }


    public void initView(View root){
        userNumber= getArguments().getString("userNumber");
        refreshLayout = root.findViewById(R.id.srl_sf);
//        refreshLayout.setReboundDuration(200);//回弹动画
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(500);
                fetchData();
            }
        });
        mRecyclerView = root.findViewById(R.id.rv_fragment_system);
        mRecyclerView.setHasFixedSize(true);
        //平常的水平一个item布局的流
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

    }

    public void initData() throws NullPointerException {
        System.out.println("initData");
        collectionAdapter = new CollectionAdapter(mList);
        collectionAdapter.setOnItemClickListener(new CollectionAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity().getApplicationContext(), ReadActivity.class);
//                System.out.println(mList.get(position).getReadText());
                intent.putExtra("text", mList.get(position).getReadText());
                intent.putExtra("userNo", mList.get(position).getUserNumber());
                intent.putExtra("userNumber", userNumber);
                intent.putExtra("readId", mList.get(position).getReadId());
                System.out.println("userNumber:"+userNumber);
                startActivity(intent);
            }

            //长按
            @Override
            public void onItemLongClick(View view, int position) {
                myPopupMenu(view,userNumber,mList.get(position).getReadId());
            }
        });

        mRecyclerView.setAdapter(collectionAdapter);

    }

    private void myPopupMenu(View v,String userNumber,Integer readId) {
        //定义PopupMenu对象
        PopupMenu popupMenu = new PopupMenu(getView().getContext(), v);
        //设置PopupMenu对象的布局
        popupMenu.getMenuInflater().inflate(R.menu.toolbar_menu, popupMenu.getMenu());
        //设置PopupMenu的点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
//                Toast.makeText(getContext(), item.getItemId()+"", Toast.LENGTH_SHORT).show();
                String str = (String) item.getTitle();
                if (str.equals("取消收藏")) {
//                    Toast.makeText(getActivity(), "点击了----" + item.getTitle(), Toast.LENGTH_SHORT).show();
                    Call<ResponseBody> callCollectionList = HttpUtil.getUserService().deleteCollection(userNumber, readId);
                    callCollectionList.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            String strBack = null;
                            try {
                                strBack = response.body().string();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (strBack.equals("deleteSuccess")) {
                                Toast.makeText(getActivity(), "取消收藏成功！", Toast.LENGTH_SHORT).show();
                                fetchData();
                            } else {
                                Toast.makeText(getActivity(), "取消收藏失败！", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
                } else if (str.equals("分享至")) {
                    Toast.makeText(getActivity(), "分享成功！", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
        //显示菜单
        popupMenu.show();
    }

    public void fetchData() {
        System.out.println("fetchData");
        refreshLayout.autoRefreshAnimationOnly();
        refreshLayout.finishRefresh(1100/*,false*/);//传入false表示刷新失败//手动设置动画时长为1.1秒

        Call<ResponseBody> callCollectionList = HttpUtil.getUserService().findAllArticle(userNumber);
        callCollectionList.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String strBack = response.body().string();
//                    System.out.println(strBack);
                    JSONArray jsonObject = null;
                    Gson gson = new Gson();
                    jsonObject = new JSONArray(strBack);
                    mList = gson.fromJson(jsonObject.toString(),new TypeToken<List<ReadBean>>(){}.getType());
                    handler.sendMessage(new Message());
                    initData();
                } catch (JSONException | IOException e) {
//                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "项目分类数据请求失败");
            }

        });
//        System.out.println(mList.size());
    }
}
